<?php
namespace bibi\setup\work;
require '../../../loader.php';

use bibi\Bibi;
use bibi\provider\template\Asset;

require 'common.php';

$app = $_POST['app'];

if ($app!='admin' && $app!='web'){
    error('参数错误');
}

$appPath = ROOT.DS.APP.DS.$app;

if (!file_exists($appPath)){
    error('应用不存在');
}

try{
    $project = require($appPath.DS.'project.php');
}catch(\Exception $e){
    error($e->getMessage());
}

if ($project['status']){
    error('应用已安装');
}

$setupPath = $appPath.DS.'_setup';

if (!file_exists($setupPath)){
    error('安装目录不存在');
}

$configPath = $appPath.DS.'_setup'.DS.'config.php';

try{
    $configData  = require($configPath);
}catch(\Exception $e){
    error($e->getMessage());
}

$database = [];
if (isset($configData['driverList'])){
    $driverList = $configData['driverList'];
    
    $dbConfig = Bibi::config('database')->toArray();

    $default  = $dbConfig['default'];
    
    foreach($dbConfig as $name => $driver){
         
        if ($name == 'default') continue;
        $name  = $name == $default ? 'default' : $name;
         
        if (is_array($driver) &&  isset($driver['driver']) && in_array(strtolower($driver['driver']),$driverList)){
            
            try{
                $className  =  'bibi\database\\'.ucfirst($driver['driver']);
                $database[$name] =ucfirst($driver['driver']).'-'.$className::frontTitle($driver);
            }catch(\Exception $e){
                error($e->getMessage());
            }
        }
    }

}




$project['icon'] =  Asset::url('/webpack/',$appPath.DS.$project['icon']);
$project['database'] = $database;

success($project);